package com.ytzl.itrip.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytzl.itrip.utils.common.DigestUtil;
import com.ytzl.itrip.utils.common.DtoUtil;
import com.ytzl.itrip.utils.common.RedisAPI;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;

/**
 * Created by asus on 2018/7/17.
 */
@Controller
@RequestMapping("/api")
public class TokenController {

    @Resource
    private RedisAPI redisAPI;

    @RequestMapping("/retoken")
    @ResponseBody
    public Object retoken(HttpServletRequest request,
                          HttpServletResponse response){
        String token = request.getHeader("token");
        if (redisAPI.exists(token)){
            JSONObject json = JSON.parseObject(redisAPI.get(token));
            int gentime = 60*60*2*1000;
            String retoken = "PC:"+
                    "_"+DigestUtil.hmacSign("","yuntuzhilian")+
                    "_"+ Calendar.getInstance().getTimeInMillis()+
                    "_"+json.getString("id")+
                    "_"+DigestUtils.md5DigestAsHex(request.getHeader("user-agent").getBytes()).substring(0,6);
            // 替换header中的token
            response.setHeader("token",retoken);
            // 替换redis中的token
            redisAPI.set(retoken, json.toJSONString(),gentime);
            redisAPI.set("token:["+json.getString("userName")+"]",token,gentime);
            return DtoUtil.returnSuccess("刷新成功,新的token:",retoken);
        }else{
            return DtoUtil.returnFail("token刷新失败，请重新登录","3001");
        }
    }

}
